<?php
/**
 * Rewrite buzz permalink with '/{post_type}/%year%/%monthnum%/%day%/%buzz%/' structure
 */
function cp_rewrite_permalink($post){
	// Rewrite buzz permalink with '/buzz/%year%/%monthnum%/%day%/%buzz%/' structure
	add_rewrite_tag( "%{$post}%", '([^/]+)' );
	$extra_post_types = get_post_types( array( '_builtin' => false, 'publicly_queryable' => true ) );
	if( empty( $extra_post_types ) )
		return;
	add_rewrite_tag( '%post_type%', '('.implode('|',$extra_post_types).')' );
	add_permastruct( $post, "/%post_type%/%year%/%monthnum%/%day%/%{$post}%/", true, 1 );
	add_rewrite_rule("{$post}" . '$', "index.php?pagename={$post}", "top");
	global $wp_rewrite;
	$wp_rewrite->flush_rules(); // !!!
}

/**
 * Define a permalink structure with a date 
 */

function cp_post_type_permalink($link, $post, $leavename, $sample ){
  $post_type_tag = '%'.$post->post_type .'%';
  $rewritecode = array(
    '%year%',
    '%monthnum%',
    '%day%',
    '%hour%',
    '%minute%',
    '%second%',
    $leavename? '' : '%postname%',
    '%post_id%',
    '%post_type%',
    $leavename? '' : '%pagename%',
    $leavename? '' : $post_type_tag,
  );
  $unixtime = strtotime($post->post_date);
  $date = explode(' ', date('Y m d H i s', $unixtime));
  $replace_array = array(
    $date[0],
    $date[1],
    $date[2],
    $date[3],
    $date[4],
    $date[5],
    $post->post_name,
    $post->ID,
    $post->post_type,
    $post->post_name,
    $post->post_name,
  );
  $path = str_replace($rewritecode, $replace_array, $link);
  return $path;
}

/**
 * Gets a list of custom taxomomies by type
 * @param $type the type of the taxonomy
 */
function cp_get_taxonomies($type){
	global $wpdb;
	$res = $wpdb->get_results($wpdb->prepare("SELECT t.term_id, t.name, t.slug FROM $wpdb->terms as t LEFT JOIN $wpdb->term_taxonomy tt ON t.term_id=tt.term_id WHERE tt.taxonomy=%s;", $type));
	return $res;
}

function cp_get_taxonomy_slug($term_id){
	global $wpdb;
	$res = $wpdb->get_results($wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE term_id=%s LIMIT 1;", $term_id));
	$res=$res[0];
	return $res->slug;
}

function cp_get_taxonomy_children($type, $parent_id){
	global $wpdb;
	if($parent_id!='-1'){
		$res = $wpdb->get_results($wpdb->prepare("SELECT t.term_id, t.name, t.slug FROM $wpdb->terms as t LEFT JOIN $wpdb->term_taxonomy tt ON t.term_id=tt.term_id WHERE tt.taxonomy=%s AND tt.parent=%s;", $type, $parent_id));
	}else{
		$res = $wpdb->get_results($wpdb->prepare("SELECT t.term_id, t.name, t.slug FROM $wpdb->terms as t LEFT JOIN $wpdb->term_taxonomy tt ON t.term_id=tt.term_id WHERE tt.taxonomy=%s;", $type));
	}
	return $res;
}
?>